package top.myhdg.bijou.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;

import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import java.util.ArrayList;

import top.myhdg.bijou.R;
import top.myhdg.bijou.colorUi.util.SharedPreferencesMgr;
import top.myhdg.bijou.utils.MyHdgUtils;

public class SettingsActivity extends BaseActivity {
    Button buttonEngine;
    Button buttonTopContent;
    Button buttonClearData;
    Switch switchPaste;
    Switch switchNight;
    Switch switchDropDown;
    Switch switchSlideHori;
    Switch switchSlideVert;
    Switch switchVolKey;
    Switch switchGeo;
    Switch switchNoTrack;
    Switch switchIntercept;
    Switch switchJavaScript;
    Switch switchRecovery;
    Button buttonSupport;
    Button buttonAbout;
    Button exitSettings;

    String engine = "";//引擎
    String topContent = "";//顶栏内容

    boolean clearCache;
    boolean clearFormData;
    boolean clearHistory;
    boolean clearStorage;
    boolean clearCookies;

    SharedPreferences configure;//设置配置文件
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        findViews();

        setListeners();
    }

    private void findViews() {
        buttonEngine = findViewById(R.id.buttonEngine);
        buttonTopContent = findViewById(R.id.buttonTopContent);
        buttonClearData = findViewById(R.id.buttonClearData);
        switchPaste = findViewById(R.id.switchPaste);
        switchNight = findViewById(R.id.switchNight);
        switchDropDown = findViewById(R.id.switchDropDown);
        switchSlideHori = findViewById(R.id.switchSlideHori);
        switchSlideVert = findViewById(R.id.switchSlideVert);
        switchVolKey = findViewById(R.id.switchVolKey);
        switchGeo = findViewById(R.id.switchGeo);
        switchNoTrack = findViewById(R.id.switchNoTrack);
        switchIntercept = findViewById(R.id.switchIntercept);
        switchJavaScript = findViewById(R.id.switchJavaScript);
        switchRecovery = findViewById(R.id.switchRecovery);
        buttonSupport = findViewById(R.id.buttonSupport);
        buttonAbout = findViewById(R.id.buttonAbout);
        exitSettings = findViewById(R.id.exitSettings);
    }

    private void setListeners() {
        configure = getSharedPreferences("BijouConfigure", MODE_PRIVATE);

        editor = configure.edit();
        engine = configure.getString("Engine", "http://www.baidu.com/s?wd=");
        topContent = configure.getString("TopContent", "title");
        clearCache = configure.getBoolean("ClearCache", true);
        clearFormData = configure.getBoolean("ClearFormdata", false);
        clearHistory = configure.getBoolean("ClearHistory", false);
        clearStorage = configure.getBoolean("ClearStorage", true);
        clearCookies = configure.getBoolean("ClearCookies", false);

        buttonEngine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String[] items = new String[]{"百度", "必应", "搜狗", "自定义"};
                int checkedIndex;
                switch (engine) {
                    case "http://www.baidu.com/s?wd=":
                        checkedIndex = 0;
                        break;
                    case "http://cn.bing.com/search?q=":
                        checkedIndex = 1;
                        break;
                    case "http://www.sogou.com/web?query=":
                        checkedIndex = 2;
                        break;
                    default:
                        checkedIndex = 3;
                }
                new QMUIDialog.CheckableDialogBuilder(SettingsActivity.this)
                        .setCheckedIndex(checkedIndex)
                        .addItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        engine = "http://www.baidu.com/s?wd=";
                                        break;
                                    case 1:
                                        engine = "http://cn.bing.com/search?q=";
                                        break;
                                    case 2:
                                        engine = "http://www.sogou.com/web?query=";
                                        break;
                                    default:
                                        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(SettingsActivity.this);
                                        builder.setTitle("自定义引擎")
                                                .setPlaceholder("在这里输入自定义引擎，请确保正确")
                                                .setDefaultText(engine)
                                                .setCanceledOnTouchOutside(false)
                                                .setInputType(InputType.TYPE_CLASS_TEXT)
                                                .addAction("取消", new QMUIDialogAction.ActionListener() {
                                                    @Override
                                                    public void onClick(QMUIDialog dialog, int index) {
                                                        MyHdgUtils.closeKeyboard(SettingsActivity.this, builder.getEditText());
                                                        dialog.dismiss();
                                                    }
                                                })
                                                .addAction("应用", new QMUIDialogAction.ActionListener() {
                                                    @Override
                                                    public void onClick(QMUIDialog dialog, int index) {
                                                        CharSequence text = builder.getEditText().getText();
                                                        if (text != null && text.length() > 0) {
                                                            engine = String.valueOf(text);
                                                            editor.putString("Engine", engine);
                                                            showTipDialog(0, "自定义引擎应用成功");
                                                            dialog.dismiss();
                                                        } else {
                                                            engine = "http://www.baidu.com/s?wd=";
                                                            editor.putString("Engine", engine);
                                                            showTipDialog(1, "不规则输入，引擎恢复默认");
                                                        }
                                                    }
                                                })
                                                .create().show();
                                }
                                if (which < 3) {
                                    editor.putString("Engine", engine);
                                }
                                dialog.dismiss();
                            }
                        })
                        .create().show();
            }
        });

        buttonTopContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String[] items = new String[]{"标题", "网址", "域名"};
                int checkedIndex;
                switch (topContent) {
                    case "title":
                        checkedIndex = 0;
                        break;
                    case "website":
                        checkedIndex = 1;
                        break;
                    default:
                        checkedIndex = 2;
                }
                new QMUIDialog.CheckableDialogBuilder(SettingsActivity.this)
                        .setCheckedIndex(checkedIndex)
                        .addItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        topContent = "title";
                                        break;
                                    case 1:
                                        topContent = "website";
                                        break;
                                    case 2:
                                        topContent = "domain";
                                        break;
                                }
                                editor.putString("TopContent", topContent);

                                dialog.dismiss();
                            }
                        })
                        .create().show();
            }
        });

        buttonClearData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String[] items = new String[]{"缓存", "表单数据", "历史记录", "网页存储", "Cookies"};
                ArrayList<Integer> checkedList = new ArrayList<>();
                if (clearCache) {
                    checkedList.add(0);
                }
                if (clearFormData) {
                    checkedList.add(1);
                }
                if (clearHistory) {
                    checkedList.add(2);
                }
                if (clearStorage) {
                    checkedList.add(3);
                }
                if (clearCookies) {
                    checkedList.add(4);
                }
                int[] checkedItems = new int[checkedList.size()];
                for (int i = 0; i < checkedList.size(); i++) {
                    checkedItems[i] = checkedList.get(i);
                }
                final QMUIDialog.MultiCheckableDialogBuilder builder = new QMUIDialog.MultiCheckableDialogBuilder(SettingsActivity.this)
                        .setCheckedItems(checkedItems)
                        .addItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        clearCache = !clearCache;
                                        break;
                                    case 1:
                                        clearFormData = !clearFormData;
                                        break;
                                    case 2:
                                        clearHistory = !clearHistory;
                                        break;
                                    case 3:
                                        clearStorage = !clearStorage;
                                        break;
                                    default:
                                        clearCookies = !clearCookies;
                                }
                            }
                        });
                builder.addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                });
                builder.addAction(0, "清除", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        editor.putBoolean("ClearCache", clearCache);
                        editor.putBoolean("ClearFormdata", clearFormData);
                        editor.putBoolean("ClearHistory", clearHistory);
                        editor.putBoolean("ClearStorage", clearStorage);
                        editor.putBoolean("ClearCookies", clearCookies);

                        Intent intent = new Intent();
                        intent.putExtra("ClearCache", clearCache);
                        intent.putExtra("ClearFormdata", clearFormData);
                        intent.putExtra("ClearHistory", clearHistory);
                        intent.putExtra("ClearStorage", clearStorage);
                        intent.putExtra("ClearCookies", clearCookies);
                        setResult(1, intent);

                        showTipDialog(2, "将在设置关闭后清除选中项");

                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        });

        boolean paste = configure.getBoolean("Paste", false);
        switchPaste.setChecked(paste);
        switchPaste.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                editor.putBoolean("Paste", isChecked);
            }
        });

        boolean night = SharedPreferencesMgr.getBoolean("NightAuto", true);
        switchNight.setChecked(night);
        switchNight.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                SharedPreferencesMgr.setBoolean("NightAuto", isChecked);
                showTipDialog(2, "重启浏览器生效");
            }
        });

        boolean dropdown = configure.getBoolean("Dropdown", false);
        switchDropDown.setChecked(dropdown);
        switchDropDown.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                editor.putBoolean("Dropdown", isChecked);
            }
        });

        boolean slideHori = configure.getBoolean("SlideHori", false);
        switchSlideHori.setChecked(slideHori);
        switchSlideHori.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                editor.putBoolean("SlideHori", isChecked);
            }
        });

        boolean slideVert = configure.getBoolean("SlideVert", false);
        switchSlideVert.setChecked(slideVert);
        switchSlideVert.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                editor.putBoolean("SlideVert", isChecked);
            }
        });

        boolean volKey = configure.getBoolean("VolKey", false);
        switchVolKey.setChecked(volKey);
        switchVolKey.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                editor.putBoolean("VolKey", isChecked);
            }
        });

        boolean geo = configure.getBoolean("Geo", true);
        switchGeo.setChecked(geo);
        switchGeo.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                editor.putBoolean("Geo", isChecked);
            }
        });

        boolean noTrack = configure.getBoolean("NoTrack", true);
        switchNoTrack.setChecked(noTrack);
        switchNoTrack.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                editor.putBoolean("NoTrack", isChecked);
            }
        });

        boolean intercept = configure.getBoolean("Intercept", true);
        switchIntercept.setChecked(intercept);
        switchIntercept.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                editor.putBoolean("Intercept", isChecked);
            }
        });

        boolean javaScript = configure.getBoolean("JavaScript", true);
        switchJavaScript.setChecked(javaScript);
        switchJavaScript.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                editor.putBoolean("JavaScript", isChecked);
            }
        });

        boolean recovery = configure.getBoolean("Recovery", false);
        switchRecovery.setChecked(recovery);
        switchRecovery.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                editor.putBoolean("Recovery", isChecked);
                showTipDialog(0, "重启浏览器生效");
            }
        });

        buttonSupport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SettingsActivity.this, SupportActivity.class);
                startActivityForResult(intent, 0);
            }
        });

        buttonAbout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SettingsActivity.this, AboutActivity.class);
                startActivityForResult(intent, 0);
            }
        });

        exitSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor.apply();

                SettingsActivity.this.finish();
            }
        });
    }

    private void showTipDialog(int mode, String text) {
        final QMUITipDialog tipDialog;
        switch (mode) {
            case 0://成功提示
                tipDialog = new QMUITipDialog.Builder(SettingsActivity.this)
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
                        .setTipWord(text)
                        .create();
                break;
            case 1://失败提示
                tipDialog = new QMUITipDialog.Builder(SettingsActivity.this)
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                        .setTipWord(text)
                        .create();
                break;
            default://自定义提示
                tipDialog = new QMUITipDialog.Builder(SettingsActivity.this)
                        .setTipWord(text)
                        .create();
                break;
        }
        tipDialog.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                tipDialog.dismiss();
            }
        }, 900);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0 && resultCode == 1) {
            setResult(5);
            SettingsActivity.this.finish();
        }
        if (requestCode == 0 && resultCode == 2) {
            setResult(6);
            SettingsActivity.this.finish();
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        editor.apply();//提交配置文件

        //==========返回当前需要清除的数据==========
        Intent intent = new Intent();
        intent.putExtra("Exit", true);
        setResult(0, intent);
        //==========返回当前需要清除的数据==========

        super.onDestroy();
    }
}
